/*
 * Date：10/23/18 9:59 PM
 * Author: guomw
 *
 */

package com.treasure.mall.biz.entity.auth;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.treasure.mall.biz.base.UserDetails;
import com.treasure.mall.biz.entity.Base2PO;
import com.treasure.mall.zbq.common.constant.Constant;
import com.treasure.mall.zbq.common.ienum.auth.RoleEnum;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;

/**
 * 系统管理员
 *
 * @author guomw
 * @date 2018/9/17
 */
@Entity
@Data
@Table(name = "sys_manager")
public class SystemManager extends Base2PO implements UserDetails {

    /**
     * ID
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "user_id")
    private Integer userId;

    /**
     * 用户所属角色
     */
    @JoinColumn(name = "role_id", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
    @ManyToOne(cascade = CascadeType.REFRESH)
    private SystemRole role;

    /**
     * 所属ID
     */
    @Column(name = "parent_user_id")
    private Integer parentUserId;

    /**
     * 用户名
     */
    @Column(name = "login_name", length = 30)
    private String loginName;

    /**
     * 密码
     */
    @Column(name = "login_pwd", length = 100)
    private String loginPwd;


    /**
     * 最后登录时间
     */
    @JsonFormat(pattern = Constant.DATETIME_FORMAT)
    @Column(name = "last_login_time", columnDefinition = Constant.DATE_COLUMN_DEFINITION)
    private LocalDateTime lastLoginTime;

    /**
     * 是否启用
     */
    @Column(name = "enable")
    private boolean enable;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        return Collections.singletonList(new SimpleGrantedAuthority(RoleEnum.ADMIN.getCode()));
    }

    @Override
    public String getPassword() {
        return this.getLoginPwd();
    }

    @Override
    public String getUsername() {
        return this.getLoginName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.isEnable();
    }

    @Override
    public RoleEnum getRoleType() {
        return RoleEnum.ADMIN;
    }

    @Override
    public Long getId() {
        return Long.valueOf(userId);
    }

    @Override
    public String getDisplayName() {
        return loginName;
    }
}
